package com.klangner.lc;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class Page {

	/** page width */
	private int	width;
	/** points */
	private Vector<Point1D>		points;
	
	/**
	 * constructor
	 */
	public Page(){
		width = 0;
	}
	
	/**
	 * Compare
	 * @param page
	 * @return
	 */
	public boolean equals(Page page){
		
		if(page.getPoints().size() != points.size())
			return false;
		
		Iterator<Point1D>	points2 = page.getPoints().iterator();
		for(int i = 0; i < points.size(); i++){
		
			Point1D p1 = points.get(i);
			Point1D p2 = points2.next();
			
			if(p1.getPosition() != p2.getPosition())
				return false;
		}
		
		
		return true;
	}
	
	/**
	 * @return points
	 */
	public Collection<Point1D> getPoints(){
		return points;
	}
	
	/**
	 * @return width
	 */
	public int	getWidth(){
		return width;
	}
	
	/**
	 * set width
	 */
	public void setWidth(int width){
		this.width = width;
	}
	
	/**
	 * Load page data from XML file
	 * @param file
	 */
	public void load(File file){
		
		 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
     DocumentBuilder 				docBuilder;
     Element								root;
     NodeList								nodes;
     Point1D								point;

     try {
    	 docBuilder = dbfac.newDocumentBuilder();
	     Document doc = docBuilder.parse(file);
	     root = doc.getDocumentElement();
	     width = Integer.parseInt( root.getAttribute("width") );
	     
	     points = new Vector<Point1D>();
	     nodes = doc.getElementsByTagName("point");
	     for(int i = 0; i < nodes.getLength(); i++){
	    	 Element pointNode = (Element)nodes.item(i);
	    	 point = new Point1D(
	    			 pointNode.getAttribute("id"), 
	    			 Integer.parseInt( pointNode.getAttribute("x") ));
	    	 points.add(point);
	     }
	     
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public String toString(){
		String text;
		
		text = "width  = " + width;
		
		return text;
	}
}
